#include "CP_Dialogs.h"
#include <cstring>
#include <cmath>

#import <AppKit/NSOpenPanel.h>

#import <AppKit/NSSavePanel.h>

#import <AppKit/NSWindow.h>
#import <AppKit/NSWindowController.h>
#import <AppKit/NSColor.h>
#import <AppKit/NSColorSpace.h>
#import <AppKit/NSColorPanel.h>

int open_file_dialog(char* result, int result_size, OpenFileOptions* options)
{
    OpenFileOptions o;
    if(options != NULL)
        o = *options;
    else
        o = make_open_options();
    
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setAllowsMultipleSelection:NO];
    
    if(o.title != NULL)
        [panel setTitle:[NSString stringWithCString: o.title encoding:NSASCIIStringEncoding]];
    
    if(o.choose_files)
        [panel setCanChooseFiles:YES];
    else
        [panel setCanChooseFiles:NO];
        
    if(o.choose_directories)
        [panel setCanChooseDirectories:YES];
    else
        [panel setCanChooseDirectories:NO];
        
    if(o.show_hidden)
        [panel setShowsHiddenFiles:YES];
    else
        [panel setShowsHiddenFiles:NO];
    
    
    if(o.allowed_extensions_OSX != NULL)
    {
        int i;
        NSMutableArray* a = [[NSMutableArray alloc] init];
        
        for(i = 0; i < o.num_allowed_extensions_OSX; i++)
        {
            [a addObject: [NSString stringWithCString: o.allowed_extensions_OSX[i] encoding:NSASCIIStringEncoding]];
        }
        
        [panel setAllowedFileTypes: a ];
        [a release];
    }

    NSInteger button = [panel runModal];

    if(button == NSFileHandlingPanelOKButton)
    {
        for(NSURL* url in [panel URLs])
        {
            if(result != NULL)
                strncpy(result, [[url path] UTF8String], result_size);
            return 1;
        }
    }
    
    return 0;
}

int open_files_dialog(char** result, int max_results, int result_size, OpenFileOptions* options)
{
    OpenFileOptions o;
    if(options != NULL)
        o = *options;
    else
        o = make_open_options();
        
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setAllowsMultipleSelection:YES];
    
    if(o.title != NULL)
        [panel setTitle:[NSString stringWithCString: o.title encoding:NSASCIIStringEncoding]];
    
    if(o.choose_files)
        [panel setCanChooseFiles:YES];
    else
        [panel setCanChooseFiles:NO];
        
    if(o.choose_directories)
        [panel setCanChooseDirectories:YES];
    else
        [panel setCanChooseDirectories:NO];
        
    if(o.show_hidden)
        [panel setShowsHiddenFiles:YES];
    else
        [panel setShowsHiddenFiles:NO];
    
    
    if(o.allowed_extensions_OSX != NULL)
    {
        int i;
        NSMutableArray* a = [[NSMutableArray alloc] init];
        
        for(i = 0; i < o.num_allowed_extensions_OSX; i++)
        {
            [a addObject: [NSString stringWithCString: o.allowed_extensions_OSX[i] encoding:NSASCIIStringEncoding]];
        }
        
        
        [panel setAllowedFileTypes: a ];
        [a release];
    }

    NSInteger button = [panel runModal];
    
    
    if(button == NSFileHandlingPanelOKButton)
    {
        int i = 0;
        for(NSURL* url in [panel URLs])
        {
            if(i >= max_results)
                break;
            if(result != NULL && result[i] != NULL)
                strncpy(result[i], [[url path] UTF8String], result_size);
            i++;
        }
        
        return i;
    }
    
    return 0;
}

int save_file_dialog(char* result, int result_size, SaveFileOptions* options)
{
    SaveFileOptions o;
    if(options != NULL)
        o = *options;
    else
        o = make_save_options();
    
    NSSavePanel *panel = [NSSavePanel savePanel];
    [panel setCanCreateDirectories:YES];
    [panel setCanSelectHiddenExtension:YES];
    [panel setTreatsFilePackagesAsDirectories:YES];
    
    
    if(o.title != NULL)
        [panel setTitle:[NSString stringWithCString: o.title encoding:NSASCIIStringEncoding]];
        
    if(o.show_hidden)
        [panel setShowsHiddenFiles:YES];
    else
        [panel setShowsHiddenFiles:NO];
    
    
    if(o.allowed_extensions_OSX != NULL)
    {
        int i;
        NSMutableArray* a = [[NSMutableArray alloc] init];
        
        for(i = 0; i < o.num_allowed_extensions_OSX; i++)
        {
            [a addObject: [NSString stringWithCString: o.allowed_extensions_OSX[i] encoding:NSASCIIStringEncoding]];
        }
        
        
        [panel setAllowedFileTypes: a ];
        [a release];
    }

    NSInteger button = [panel runModal];

    if(button == NSFileHandlingPanelOKButton)
    {
        if(result != NULL)
            strncpy(result, [[[panel URL] path] UTF8String], result_size);
        return 1;
    }
    
    return 0;
}


@interface MyWindowController : NSWindowController <NSWindowDelegate> {
    NSWindow *_myWindow;
}

@property (nonatomic, retain) IBOutlet NSWindow *myWindow;

@end


@implementation MyWindowController

@synthesize myWindow = _myWindow;

- (void)dealloc {
    [_myWindow release];
    [super dealloc];
}

- (void)windowWillClose:(NSNotification *)notification {
   [NSApp stopModal];
}

@end



// This *SHOULD* have an OK and Cancel button, but I think that would require embedding the color panel in another window and I have no skill in Obj-C.
// For now, it just returns the color when the dialog is closed.
int color_picker_dialog(int* r, int* g, int* b, int* a, ColorPickerOptions* options)
{
    ColorPickerOptions o;
    if(options != NULL)
        o = *options;
    else
        o = make_color_picker_options();
    
    MyWindowController* controller = [[MyWindowController alloc] init];

    NSColorPanel* panel = [NSColorPanel sharedColorPanel];
    
    if(o.use_alpha && a != NULL)
        [panel setShowsAlpha:YES];
    else
        [panel setShowsAlpha:NO];
    
    [panel setDelegate:controller];
    
    NSModalSession session = [NSApp beginModalSessionForWindow:panel];
    
    [panel orderFront:panel];
    
    while([NSApp runModalSession:session] == NSRunContinuesResponse)
        continue;
    
    int result = 0;

    {
        NSColorSpace *colorSpace = [NSColorSpace genericRGBColorSpace];
        
        NSColor* color = [[panel color] colorUsingColorSpace:colorSpace];
        
        if(r != NULL)
            *r = round([color redComponent] * 255);
        if(g != NULL)
            *g = round([color greenComponent] * 255);
        if(b != NULL)
            *b = round([color blueComponent] * 255);
        if(a != NULL)
        {
            if(o.use_alpha)
                *a = round([color alphaComponent] * 255);
            else
                *a = 255;
        }
        
        result = 1;
    }
    
    [NSApp endModalSession:session];
    [NSApp stopModal];
    [panel orderOut:panel];
    [panel close];
    [controller release];
    
    return result;
}
